<?php

class KefuAction extends PublicAction
{
    protected $kefuModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->kefuModel = D('Kefu');
    }

    //列表页
    public function index()
    {
        $list = $this->kefuModel->order('listorder desc,id asc')->select();

        $this->assign('list', $list);

        //记录当前位置
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->display();
    }

    //新增
    public function add()
    {
        if (IS_POST) {

            if (false === $this->kefuModel->create()) {
                $this->error($this->kefuModel->getError());
            }

            if ($this->kefuModel->add()) {
                $this->success('修改成功！', cookie('__forward__'));
            } else {
                $this->error('修改失败: ' . $this->kefuModel->getDbError());
            }
        } else {
            $this->display();
        }
    }

    //编辑
    public function edit()
    {
        if (IS_POST) {

            if (false === $this->kefuModel->create()) {
                $this->error($this->kefuModel->getError());
            }

            // 更新数据
            if ($this->kefuModel->save()) {
                $this->success('添加成功！', cookie('__forward__'));
            } else {
                //错误提示
                $this->error('添加失败: ' . $this->kefuModel->getDbError());
            }
        } else {
            $id = I('id', 0, 'intval');

            $vo = $this->kefuModel->getById($id);
            $this->assign('vo', $vo);

            $this->display();
        }
    }

    //删除
    function delete()
    {
        $id = I('get.id', 0, 'intval');

        if (isset($id)) {
            if (false !== $this->kefuModel->delete($id)) {
                $this->success('删除失败！');
            } else {
                $this->error('删除失败！: ' . $this->kefuModel->getDbError());
            }
        } else {
            $this->error('缺少必要的参数!');
        }
    }

    //排序
    public function listorder()
    {
        $ids = $_POST['listorders'];

        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $this->kefuModel->where('id=' . $key)->save($data);
        }

        $this->success('排序成功!');
    }
}